package lk.icta.core.service.impl;

import lk.icta.common.ELandRuntimeException;
import lk.icta.common.dao.PersonDAO;
import lk.icta.common.entity.Person;
import lk.icta.core.service.PersonManagementService;
import lk.icta.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Duminda Dharmakeerthi
 */
public class PersonManagementServiceImpl implements PersonManagementService {

    private static final Logger logger = LoggerFactory.getLogger(PersonManagementServiceImpl.class);
    private final PersonDAO personDAO;

    public PersonManagementServiceImpl(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void addPerson(Person person, User user) {
        personDAO.addPerson(person, user);
        // /todo tharanga check user
        /*logger.debug("Adding a person [Name: {}\tUser: {}]", person.getName(), user.getUsername());
        if(!user.isAuthorized(Permission.PERSON_MANAGEMENT)){
            handleELandRuntimeException(user.getUsername() + " doesn't have permission to add land", ErrorCodes.UNAUTHORIZED_ACCESS);
        }else {
            personDAO.addPerson(person, user);
        }*/
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void updatePerson(Person person, User user) {

        //todo tharanga Validate user
        personDAO.updatePerson(person, user);
        /* logger.debug("Updating a person [Name: {}\tUser: {}]", person.getName(), user.getUsername());
        if (!user.isAuthorized(Permission.PERSON_MANAGEMENT)) {
            handleELandRuntimeException(user.getUsername() + " doesn't have permission to add land", ErrorCodes.UNAUTHORIZED_ACCESS);
        } else {
            personDAO.updatePerson(person, user);
        }*/
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Person getPersonByIdUKey(long id, User user) {
        logger.debug("test");
        return personDAO.getPersonById(id, user);
    }

    private void handleELandRuntimeException(String message, int code) {
        logger.error(message);
        throw new ELandRuntimeException(message, code);
    }
}
